package apis.amapv2.com.handlerthread;

import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;

/**
 * HandlerThreadActivity
 */
@RequiresApi(api = Build.VERSION_CODES.CUPCAKE)
public class HandlerThreadActivity extends AppCompatActivity implements View.OnClickListener {

    //1、主线程的Handler
    private Handler.Callback mCallbackMain = new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {

            return false;
        }
    };
    private Handler mHandlerMain = new Handler(mCallbackMain);

    //2、子线程的Handler
    private HandlerThread mHandlerThread;
    private Handler mHandler;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_handler_thread);

        initView();

        initThreadHandler();
    }

    private void initView() {
        findViewById(R.id.btn1).setOnClickListener(this);
        findViewById(R.id.btn2).setOnClickListener(this);
    }

    private void initThreadHandler() {
        //HandlerThread的优点
        //1、HandlerThread将loop转移到子线程，分担了主线程的压力
        //2、HandlerThread拥有自己的消息队列，不会干扰或者阻塞UI线程。

        //1、创建一个线程，线程的名字 handler-thread
        mHandlerThread = new HandlerThread("handler-thread");

        //2、开启一个线程
        mHandlerThread.start();

        //3、在这个线程中创建一个Handler对象
        mHandler = new Handler( mHandlerThread.getLooper() ){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                Toast.makeText(HandlerThreadActivity.this, "子线程接受到了数据！", Toast.LENGTH_SHORT).show();
            }
        };
    }

    @RequiresApi(api = Build.VERSION_CODES.ECLAIR)
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHandlerThread.quit();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.btn1) {//在主线程给子线程发送数据
            mHandler.sendEmptyMessage(1);
        } else if (id == R.id.btn2) {//在子线程给子线程发送数据
            new Thread(new Runnable() {
                @Override
                public void run() {
                    mHandler.sendEmptyMessage(2);//在子线程给子线程发送数据
                }
            }).start();
        }
    }
}
